<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="proId">
        <el-select
          v-model="queryParams.proId"
          placeholder="请选择项目"
          clearable
          filterable
          remote
          :remote-method="getProjectList"
          :loading="projectLoading"
          style="width: 180px;"
        >
          <el-option
            v-for="project in projectList"
            :key="project.id"
            :label="project.proName"
            :value="project.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="激活码" prop="activeCode">
        <el-input
          v-model="queryParams.activeCode"
          placeholder="请输入激活码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 150px;">
          <el-option label="未使用" value="0" />
          <el-option label="已使用" value="1" />
          <el-option label="已过期" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="禁用状态" prop="disabled">
        <el-select v-model="queryParams.disabled" placeholder="请选择禁用状态" clearable style="width: 150px;">
          <el-option label="启用" value="0" />
          <el-option label="禁用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['machine:activationCode:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['machine:activationCode:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['machine:activationCode:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['machine:activationCode:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="MagicStick"
          @click="handleBatchGenerate"
          v-hasPermi="['machine:activationCode:batchGenerate']"
        >批量生成</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="User"
          :disabled="multiple"
          @click="handleAllocate"
          v-hasPermi="['machine:activationCode:allocate']"
        >分配给用户</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="UserFilled"
          @click="handleBatchAllocate"
          v-hasPermi="['machine:activationCode:batchAllocate']"
        >批量分配</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activationCodeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" width="50" align="center" prop="id" />
      <el-table-column label="项目名称" align="center" width="120">
        <template #default="scope">
          {{ getProjectName(scope.row.proId) || scope.row.proName }}
        </template>
      </el-table-column>
      <el-table-column label="激活码" align="center" prop="activeCode" width="330" show-overflow-tooltip />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <span v-if="scope.row.status === 0" style="color: #1890ff;">未使用</span>
          <span v-else-if="scope.row.status === 1" style="color: #52c41a;">已使用</span>
          <span v-else-if="scope.row.status === 2" style="color: #ff4d4f;">已过期</span>
        </template>
      </el-table-column>
      <el-table-column label="激活码类型" align="center" prop="activationType" width="100">
        <template #default="scope">
          <span v-if="scope.row.activationType === 'MACHINE'" style="color: #faad14;">机器码限制</span>
          <span v-else-if="scope.row.activationType === 'NORMAL'" style="color: #13c2c2;">无限制</span>
        </template>
      </el-table-column>
      <el-table-column label="禁用状态" align="center" prop="disabled" width="80">
        <template #default="scope">
          <span v-if="scope.row.disabled === 0" style="color: #52c41a;">启用</span>
          <span v-else-if="scope.row.disabled === 1" style="color: #ff4d4f;">禁用</span>
        </template>
      </el-table-column>
      <el-table-column label="积分" align="center" prop="mark" width="60" />
      <el-table-column label="有效类型" align="center" width="80">
        <template #default="scope">
          <span v-if="scope.row.validityType === 'minute'">分钟</span>
          <span v-else-if="scope.row.validityType === 'hour'">小时</span>
          <span v-else-if="scope.row.validityType === 'day'">天</span>
          <span v-else-if="scope.row.validityType === 'month'">月</span>
          <span v-else-if="scope.row.validityType === 'year'">年</span>
          <span v-else-if="scope.row.validityType === 'permanent'">永久</span>
        </template>
      </el-table-column>
      <el-table-column label="有效值" align="center" prop="validityValue" width="80" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="分配用户" align="center" prop="allocateUserName" width="100" show-overflow-tooltip />
      
      <el-table-column label="分配时间" align="center" prop="updateTime" width="160">
        <template #default="scope">
          <span v-if="scope.row.updateTime">{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['machine:activationCode:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['machine:activationCode:remove']">删除</el-button>
          <el-button link type="primary" icon="User" @click="handleSingleAllocate(scope.row)" v-hasPermi="['machine:activationCode:allocate']" v-if="!scope.row.allocateUserId && scope.row.status !== 1">分配</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改激活码对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="activationCodeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目名称" prop="proId">
          <el-select
            v-model="form.proId"
            placeholder="请选择项目"
            filterable
            remote
            :remote-method="getProjectList"
            :loading="projectLoading"
            style="width: 100%;"
          >
            <el-option
              v-for="project in projectList"
              :key="project.id"
              :label="project.proName"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="有效期" prop="validValue">
          <el-row :gutter="10">
            <el-col :span="16">
              <el-input v-model.number="form.validValue" type="number" min="1" placeholder="请输入有效期数值" :disabled="form.validUnit === 'PERMANENT'" />
            </el-col>
            <el-col :span="8">
              <el-select v-model="form.validUnit" placeholder="有效期类型" style="width: 100%;" @change="handleValidUnitChange">
                <el-option label="分钟" value="MINUTE" />
                <el-option label="小时" value="HOUR" />
                <el-option label="天" value="DAY" />
                <el-option label="月" value="MONTH" />
                <el-option label="年" value="YEAR" />
                <el-option label="永久" value="PERMANENT" />
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="积分" prop="mark">
          <el-input v-model.number="form.mark" type="number" min="0" placeholder="请输入积分值" />
        </el-form-item>
        <el-form-item label="激活码类型" prop="activationType">
          <el-select v-model="form.activationType" placeholder="请选择激活码类型" style="width: 100%;">
            <el-option label="机器码限制" value="MACHINE" />
            <el-option label="无限制" value="NORMAL" />
          </el-select>
        </el-form-item>
        <el-form-item label="禁用状态" prop="disabled">
          <el-switch v-model="form.disabled" active-value="1" inactive-value="0" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量生成激活码对话框 -->
    <el-dialog title="批量生成激活码" v-model="batchGenerateOpen" width="600px" :fullscreen="false" append-to-body style="min-height: 350px;">
      <div class="batch-generate-container">
        <el-form ref="batchFormRef" :model="batchForm" :rules="batchRules" label-width="100px" class="batch-form">
          <el-form-item label="项目名称" prop="proId">
            <el-select
              v-model="batchForm.proId"
              placeholder="请选择项目"
              filterable
              remote
              :remote-method="getProjectList"
              :loading="projectLoading"
              style="width: 100%;"
            >
              <el-option
                v-for="project in projectList"
                :key="project.id"
                :label="project.proName"
                :value="project.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="生成数量" prop="count">
            <el-input v-model.number="batchForm.count" type="number" min="1" max="100" placeholder="请输入生成数量（1-100）" />
          </el-form-item>
          <el-form-item label="有效期" prop="validValue">
            <el-row :gutter="10">
              <el-col :span="16">
                <el-input v-model.number="batchForm.validValue" type="number" min="1" placeholder="请输入有效期数值" :disabled="batchForm.validUnit === 'PERMANENT'" />
              </el-col>
              <el-col :span="8">
                <el-select v-model="batchForm.validUnit" placeholder="有效期类型" style="width: 100%;" @change="handleBatchValidUnitChange">
                  <el-option label="分钟" value="MINUTE" />
                  <el-option label="小时" value="HOUR" />
                  <el-option label="天" value="DAY" />
                  <el-option label="月" value="MONTH" />
                  <el-option label="年" value="YEAR" />
                  <el-option label="永久" value="PERMANENT" />
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="积分" prop="mark">
            <el-input v-model.number="batchForm.mark" type="number" min="0" placeholder="请输入积分值" />
          </el-form-item>
          <el-form-item label="激活码类型" prop="activationType">
            <el-select v-model="batchForm.activationType" placeholder="请选择激活码类型" style="width: 100%;">
              <el-option label="机器码限制" value="MACHINE" />
              <el-option label="无限制" value="NORMAL" />
            </el-select>
          </el-form-item>
          <el-form-item label="禁用状态" prop="disabled">
            <el-switch v-model="batchForm.disabled" active-value="1" inactive-value="0" />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchGenerate">确 定</el-button>
        <el-button @click="batchGenerateOpen = false">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- 分配激活码给用户对话框 -->
    <el-dialog title="分配激活码给用户" v-model="allocateOpen" width="500px" append-to-body>
      <el-form ref="allocateFormRef" :model="allocateForm" :rules="allocateRules" label-width="100px">
        <el-form-item label="项目名称" prop="proId">
          <el-input v-model="allocateForm.proName" disabled placeholder="项目名称" />
        </el-form-item>
        <el-form-item label="激活码数量" prop="count">
          <el-input v-model="allocateForm.count" disabled placeholder="激活码数量" />
        </el-form-item>
        <el-form-item label="分配用户" prop="allocateUserId">
          <el-select
            v-model="allocateForm.allocateUserId"
            placeholder="请选择用户"
            filterable
            remote
            :remote-method="getUserList"
            :loading="userLoading"
            style="width: 100%;"
          >
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAllocate">确 定</el-button>
        <el-button @click="allocateOpen = false">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- 批量分配激活码对话框 -->
    <el-dialog title="批量分配激活码" v-model="batchAllocateOpen" width="500px" append-to-body>
      <el-form ref="batchAllocateFormRef" :model="batchAllocateForm" :rules="batchAllocateRules" label-width="100px">
        <el-form-item label="项目名称" prop="proId">
          <el-select
            v-model="batchAllocateForm.proId"
            placeholder="请选择项目"
            filterable
            remote
            :remote-method="getProjectList"
            :loading="projectLoading"
            style="width: 100%;"
            @change="onProjectChange"
          >
            <el-option
              v-for="project in projectList"
              :key="project.id"
              :label="project.proName"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="可分配数量" prop="availableCount">
          <el-input v-model="batchAllocateForm.availableCount" disabled placeholder="可分配数量" />
        </el-form-item>
        <el-form-item label="分配数量" prop="count">
          <el-input v-model.number="batchAllocateForm.count" type="number" min="1" :max="batchAllocateForm.availableCount || 100" placeholder="请输入分配数量" />
        </el-form-item>
        <el-form-item label="分配用户" prop="allocateUserId">
          <el-select
            v-model="batchAllocateForm.allocateUserId"
            placeholder="请选择用户"
            filterable
            remote
            :remote-method="getUserList"
            :loading="userLoading"
            style="width: 100%;"
          >
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchAllocate">确 定</el-button>
        <el-button @click="batchAllocateOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.batch-generate-container {
  padding: 20px 0;
  background-color: #f9f9f9;
}

.batch-form {
  margin-top: 10px;
}

.dialog-footer {
  text-align: right;
  padding: 15px 20px;
  border-top: 1px solid #e9e9e9;
  margin-top: 20px;
}
</style>

<style scoped>
.batch-generate-container {
  padding: 20px 0;
  background-color: #f9f9f9;
}

.batch-form {
  margin-top: 10px;
}

.dialog-footer {
  text-align: right;
  padding: 15px 20px;
  border-top: 1px solid #e9e9e9;
  margin-top: 20px;
}
</style>

<script>
import { listActivationCode, getActivationCode, addActivationCode, updateActivationCode, delActivationCode, batchGenerateActivationCode, allocateActivationCodes, batchAllocateActivationCodes } from '@/api/machine/activationCode'
import { listProject } from '@/api/project'
import { listUser } from '@/api/system/user'

// 定义全局样式
const globalStyle = `
  /* 全局样式定义 */
`

export default {
  name: 'ActivationCode',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 项目加载状态
      projectLoading: false,
      // 用户加载状态
      userLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 激活码表格数据
      activationCodeList: [],
      // 项目列表
      projectList: [],
      // 用户列表
      userList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示批量生成弹出层
      batchGenerateOpen: false,
      // 是否显示分配弹出层
      allocateOpen: false,
      // 是否显示批量分配弹出层
      batchAllocateOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        proId: '',
        activeCode: '',
        status: '',
        disabled: '',
        createTime: '',
        expireTime: '',
        usedMachineId: ''
      },
      // 表单参数
      form: {},
      // 批量生成表单参数
      batchForm: {
        proId: '',
        count: 10,
        validValue: 30,
        validUnit: 'DAY',
        mark: 0,
        activationType: 'MACHINE',
        disabled: 0
      },
      // 分配表单参数
      allocateForm: {
        proId: '',
        proName: '',
        count: 0,
        allocateUserId: ''
      },
      // 批量分配表单参数
      batchAllocateForm: {
        proId: '',
        availableCount: 0,
        count: 1,
        allocateUserId: ''
      },
      // 表单校验
      rules: {
        proId: [
          { required: true, message: '项目名称不能为空', trigger: 'change' }
        ],
        validValue: [
          {
            validator: (rule, value, callback) => {
              if (this.form.validUnit !== 'PERMANENT' && (!value || value <= 0)) {
                callback(new Error('有效期数值不能为空且必须大于0'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        mark: [
          { required: true, message: '积分不能为空', trigger: 'blur' },
          { type: 'number', min: 0, message: '积分必须大于等于0', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'change' }
        ],
        activationType: [
          { required: true, message: '激活码类型不能为空', trigger: 'change' }
        ]
      },
      // 批量生成校验规则
      batchRules: {
        proId: [
          { required: true, message: '项目名称不能为空', trigger: 'change' }
        ],
        count: [
          { required: true, message: '生成数量不能为空', trigger: 'blur' },
          { type: 'number', min: 1, max: 100, message: '生成数量必须在1-100之间', trigger: 'blur' }
        ],
        validValue: [
          {
            validator: (rule, value, callback) => {
              if (this.form.validUnit !== 'PERMANENT' && (!value || value <= 0)) {
                callback(new Error('有效期数值不能为空且必须大于0'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        mark: [
          { required: true, message: '积分不能为空', trigger: 'blur' },
          { type: 'number', min: 0, message: '积分必须大于等于0', trigger: 'blur' }
        ],
        activationType: [
          { required: true, message: '激活码类型不能为空', trigger: 'change' }
        ]
      },
      // 单条分配按钮点击事件
      handleSingleAllocate(row) {
        // 检查激活码是否已分配
        if (row.allocateUserId) {
          this.$notify({
            title: '提示',
            message: '该激活码已分配，请重新选择',
            type: 'warning'
          })
          return
        }
        
        // 检查激活码是否已使用
        if (row.status === 1) {
          this.$notify({
            title: '提示',
            message: '该激活码已使用，请重新选择',
            type: 'warning'
          })
          return
        }
        
        // 获取项目名称
        const project = this.projectList.find(item => item.id === row.proId)
        
        this.allocateForm = {
          proId: row.proId,
          proName: project ? project.proName : '',
          count: 1,
          allocateUserId: ''
        }
        
        // 设置要分配的ID
        this.ids = [row.id]
        
        this.allocateOpen = true
        this.getUserList()
      },
      
      // 分配给用户校验规则
      allocateRules: {
        allocateUserId: [
          { required: true, message: '分配用户不能为空', trigger: 'change' }
        ]
      },
      // 批量分配校验规则
      batchAllocateRules: {
        proId: [
          { required: true, message: '项目名称不能为空', trigger: 'change' }
        ],
        count: [
          { required: true, message: '分配数量不能为空', trigger: 'blur' },
          { type: 'number', min: 1, message: '分配数量必须大于0', trigger: 'blur' }
        ],
        allocateUserId: [
          { required: true, message: '分配用户不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    // 添加全局样式
    const style = document.createElement('style')
    style.type = 'text/css'
    style.appendChild(document.createTextNode(globalStyle))
    document.head.appendChild(style)
    this.getProjectList()
    this.getList()
  },
  methods: {
    /** 查询激活码列表 */
    getList() {
      this.loading = true
      listActivationCode(this.queryParams).then(response => {
        if (response && response.rows) {
          this.activationCodeList = response.rows
          this.total = response.total
        } else {
          this.activationCodeList = []
          this.total = 0
          this.$notify({
            title: '提示',
            message: '获取数据失败，返回格式不正确',
            type: 'warning'
          })
        }
        this.loading = false
      }).catch(error => {
        this.loading = false
        this.$notify({
          title: '错误',
          message: '获取激活码列表失败，请稍后重试',
          type: 'error'
        })
        console.error('获取激活码列表失败:', error)
      })
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 获取项目列表 */
    getProjectList(query) {
      this.projectLoading = true
      listProject(query).then(response => {
        if (response && response.rows) {
          this.projectList = response.rows.map(item => ({
            id: item.id,
            proName: item.projectName ? item.projectName : item.proName
          }))
        } else {
          this.projectList = []
        }
        this.projectLoading = false
      }).catch(error => {
        this.projectLoading = false
        console.error('获取项目列表失败:', error)
      })
    },
    /** 获取用户列表 */
    getUserList(query) {
      this.userLoading = true
      listUser(query).then(response => {
        if (response && response.rows) {
          this.userList = response.rows.map(item => ({
            userId: item.userId,
            nickName: item.nickName,
            userName: item.userName
          }))
        } else {
          this.userList = []
        }
        this.userLoading = false
      }).catch(error => {
        this.userLoading = false
        console.error('获取用户列表失败:', error)
      })
    },
    /** 根据项目ID获取项目名称 */
    getProjectName(proId) {
      if (!proId) return ''
      const project = this.projectList.find(item => item.id === proId)
      return project ? project.proName : ''
    },
    /** 搜索按钮点击事件 */
    handleQuery() {
      this.queryParams.pageNum = 1
      // 搜索时不需要重新获取项目列表，避免不必要的请求
      this.getList()
    },
    /** 重置按钮点击事件 */
    resetQuery() {
      // 重置查询参数
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        proId: '',
        activeCode: '',
        status: '',
        disabled: '',
        createTime: '',
        expireTime: '',
        usedMachineId: ''
      }
      // 重置表单状态
      if (this.$refs.queryRef) {
        this.$refs.queryRef.resetFields()
      }
      // 重新查询数据
      this.getList()
    },
    /** 重置表单数据 */
    reset() {
      this.form = {}
      if (this.$refs.activationCodeRef) {
        this.resetForm('activationCodeRef')
      }
    },
    /** 新增按钮点击事件 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加激活码'
      // 初始化表单，使其与批量生成功能类似，但每次只生成一个
      this.form.validValue = 30
      this.form.validUnit = 'DAY'
      this.form.mark = 0
      // 设置默认激活码类型为机器码限制
      this.form.activationType = 'MACHINE'
    },
    /** 修改按钮点击事件 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      
      // 获取选中的行数据
      let selectedRow = null
      if (row && row.id) {
        selectedRow = row
      } else if (this.activationCodeList && this.ids.length === 1) {
        selectedRow = this.activationCodeList.find(item => item.id === this.ids[0])
      }
      
      // 检查激活码状态，如果已使用则提示并阻止修改
      if (selectedRow && selectedRow.status === 1) {
        this.$notify({
          title: '提示',
          message: '已使用的激活码不可修改',
          type: 'warning'
        })
        return
      }
      
      getActivationCode(id).then(response => {
        this.form = response.data
        // 将validityType和validityValue映射到表单的validUnit和validValue字段
        if (response.data.validityType && response.data.validityValue) {
          this.form.validUnit = response.data.validityType.toUpperCase()
          this.form.validValue = response.data.validityValue
        }
        this.open = true
        this.title = '修改激活码'
      })
    },
    /** 批量生成按钮点击事件 */
    handleBatchGenerate() {
      this.batchGenerateOpen = true
    },
    
    /** 分配给用户按钮点击事件 */
    handleAllocate() {
      if (this.ids.length === 0) {
        this.$notify({
          title: '提示',
          message: '请选择需要分配的激活码',
          type: 'warning'
        })
        return
      }
      
      // 检查选中的激活码是否已分配
      const allocatedCodes = this.activationCodeList.filter(item => this.ids.includes(item.id) && item.allocateUserId)
      if (allocatedCodes.length > 0) {
        this.$notify({
          title: '提示',
          message: '选中的激活码中包含已分配的激活码，请重新选择',
          type: 'warning'
        })
        return
      }
      
      // 检查选中的激活码是否已使用
      const usedCodes = this.activationCodeList.filter(item => this.ids.includes(item.id) && item.status === 1)
      if (usedCodes.length > 0) {
        this.$notify({
          title: '提示',
          message: '选中的激活码中包含已使用的激活码，请重新选择',
          type: 'warning'
        })
        return
      }
      
      // 获取项目名称
      const firstCode = this.activationCodeList.find(item => item.id === this.ids[0])
      const project = this.projectList.find(item => item.id === firstCode.proId)
      
      this.allocateForm = {
        proId: firstCode.proId,
        proName: project ? project.proName : '',
        count: this.ids.length,
        allocateUserId: ''
      }
      
      this.allocateOpen = true
      this.getUserList()
    },
    
    /** 批量分配按钮点击事件 */
    handleBatchAllocate() {
      this.batchAllocateForm = {
        proId: '',
        availableCount: 0,
        count: 1,
        allocateUserId: ''
      }
      this.batchAllocateOpen = true
      this.getProjectList()
      this.getUserList()
    },
    
    /** 项目选择变化事件 */
    onProjectChange(proId) {
      if (proId) {
        // 查询该项目未分配的激活码数量
        listActivationCode({
          proId: proId,
          allocateUserId: null,
          status: 0
        }).then(response => {
          this.batchAllocateForm.availableCount = response.total
        })
      } else {
        this.batchAllocateForm.availableCount = 0
      }
    },
    
    // 有效期类型变化处理函数
    handleValidUnitChange(unit) {
      // 当选择永久类型时，设置有效值为99999+
      if (unit === 'PERMANENT') {
        this.form.validValue = 99999
      } else if (!this.form.validValue || this.form.validValue <= 0) {
        this.form.validValue = 30
      }
    },
    
    // 批量生成有效期类型变化处理函数
    handleBatchValidUnitChange(unit) {
      // 当选择永久类型时，设置有效值为99999+
      if (unit === 'PERMANENT') {
        this.batchForm.validValue = 99999
      } else if (!this.batchForm.validValue || this.batchForm.validValue <= 0) {
        this.batchForm.validValue = 30
      }
    },
    
    /** 批量生成提交 */
    submitBatchGenerate() {
      this.$refs.batchFormRef.validate(valid => {
        if (valid) {
          // 验证生成数量是否在有效范围内
          if (this.batchForm.count < 1 || this.batchForm.count > 100) {
            this.$notify({
              title: '提示',
              message: '生成数量必须在1-100之间',
              type: 'warning'
            })
            return
          }
          
          // 获取项目名称
          const project = this.projectList.find(item => item.id === this.batchForm.proId)
          const proName = project ? project.proName : ''
          
          // 准备请求参数
          const batchGenerateParams = {
            count: this.batchForm.count,
            proId: this.batchForm.proId,
            proName: proName,
            mark: this.batchForm.mark || 0, // 积分值，默认为0
            validityType: this.batchForm.validUnit.toLowerCase(),
            validityValue: this.batchForm.validValue,
            activationType: this.batchForm.activationType || 'MACHINE',
            disabled: this.batchForm.disabled || 0
          }
          
          // 调用后端批量生成激活码API
          batchGenerateActivationCode(batchGenerateParams).then(() => {
            this.batchGenerateOpen = false
            this.$notify({
              title: '成功',
              message: '批量生成激活码成功',
              type: 'success'
            })
            this.getProjectList()
            this.getList()
          }).catch(error => {
            this.$notify({
              title: '错误',
              message: '批量生成失败，请稍后重试',
              type: 'error'
            })
            console.error('批量生成激活码失败:', error)
          })
        }
      })
    },
    
    /** 提交按钮 */
    submitForm() {
      this.$refs.activationCodeRef.validate(valid => {
        if (valid) {
          // 表单数据处理和转换
          const formData = { ...this.form }
          
          // 统一处理有效期数据
          if (formData.validUnit && formData.validValue) {
            formData.validityType = formData.validUnit.toLowerCase()
            formData.validityValue = formData.validValue
            delete formData.validUnit
            delete formData.validValue
          }
          
          if (formData.id != null) {
            // 修改激活码
            // 检查是否可编辑
            const currentCode = this.activationCodeList.find(item => item.id === formData.id)
            if (currentCode && !this.checkEditable(currentCode)) {
              return
            }
            
            updateActivationCode(formData).then(response => {
              if (response.code === 200) {
                this.$notify({
                  title: '成功',
                  message: '修改成功',
                  type: 'success'
                })
                this.open = false
                this.getProjectList()
                this.getList()
              } else {
                this.$notify({
                  title: '错误',
                  message: response.msg || '修改失败',
                  type: 'error'
                })
              }
            }).catch(error => {
              this.$notify({
                title: '错误',
                message: '网络请求失败，请稍后重试',
                type: 'error'
              })
              console.error('修改激活码失败:', error)
            })
          } else {
            // 添加激活码
            // 获取项目名称
            const project = this.projectList.find(item => item.id === formData.proId)
            const proName = project ? project.proName : ''
            
            // 准备请求参数，与批量生成类似但每次只生成一个
            const batchGenerateParams = {
              count: 1, // 固定为1，表示只生成一个激活码
              proId: formData.proId,
              proName: proName,
              mark: formData.mark || 0, // 积分值，默认为0
              validityType: formData.validityType,
              validityValue: formData.validityValue,
              activationType: formData.activationType || 'MACHINE',
              disabled: formData.disabled || 0
            }
            
            // 调用后端批量生成激活码API生成单个激活码
            batchGenerateActivationCode(batchGenerateParams).then(() => {
              this.open = false
              this.$notify({
                title: '成功',
                message: '添加成功',
                type: 'success'
              })
              this.getProjectList()
              this.getList()
            }).catch(error => {
              this.$notify({
                title: '错误',
                message: '添加失败，请稍后重试',
                type: 'error'
              })
              console.error('添加激活码失败:', error)
            })
          }
        }
      })
    },
    
    /** 分配提交 */
    submitAllocate() {
      this.$refs.allocateFormRef.validate(valid => {
        if (valid) {
          // 获取分配用户名
          const user = this.userList.find(item => item.userId === this.allocateForm.allocateUserId)
          const allocateUserName = user ? user.userName : ''
          
          const allocateParams = {
            ids: this.ids,
            allocateUserId: this.allocateForm.allocateUserId,
            allocateUserName: allocateUserName
          }
          
          allocateActivationCodes(allocateParams).then(response => {
            if (response.code === 200) {
              this.allocateOpen = false
              this.$notify({
                title: '成功',
                message: '分配成功',
                type: 'success'
              })
              this.getList()
            } else {
              this.$notify({
                title: '错误',
                message: response.msg || '分配失败',
                type: 'error'
              })
            }
          }).catch(error => {
            this.$notify({
              title: '错误',
              message: '网络请求失败，请稍后重试',
              type: 'error'
            })
            console.error('分配激活码失败:', error)
          })
        }
      })
    },
    
    /** 批量分配提交 */
    submitBatchAllocate() {
      this.$refs.batchAllocateFormRef.validate(valid => {
        if (valid) {
          // 验证分配数量是否超过可分配数量
          if (this.batchAllocateForm.count > this.batchAllocateForm.availableCount) {
            this.$notify({
              title: '提示',
              message: `分配数量不能超过可分配数量(${this.batchAllocateForm.availableCount})`,
              type: 'warning'
            })
            return
          }
          
          // 获取项目名称
          const project = this.projectList.find(item => item.id === this.batchAllocateForm.proId)
          const proName = project ? project.proName : ''
          
          // 获取分配用户名
          const user = this.userList.find(item => item.userId === this.batchAllocateForm.allocateUserId)
          const allocateUserName = user ? user.userName : ''
          
          const batchAllocateParams = {
            proId: this.batchAllocateForm.proId,
            count: this.batchAllocateForm.count,
            allocateUserId: this.batchAllocateForm.allocateUserId,
            allocateUserName: allocateUserName
          }
          
          batchAllocateActivationCodes(batchAllocateParams).then(response => {
            if (response.code === 200) {
              this.batchAllocateOpen = false
              this.$notify({
                title: '成功',
                message: '批量分配成功',
                type: 'success'
              })
              this.getList()
            } else {
              this.$notify({
                title: '错误',
                message: response.msg || '批量分配失败',
                type: 'error'
              })
            }
          }).catch(error => {
            this.$notify({
              title: '错误',
              message: '网络请求失败，请稍后重试',
              type: 'error'
            })
            console.error('批量分配激活码失败:', error)
          })
        }
      })
    },
    
    /** 删除按钮点击事件 */
    handleDelete(row) {
      const ids = row.id || this.ids
      const idList = Array.isArray(ids) ? ids : [ids]
      
      // 检查选中的激活码是否已使用
      const usedCodes = this.activationCodeList.filter(item => idList.includes(item.id) && item.status === 1)
      if (usedCodes.length > 0) {
        this.$notify({
          title: '提示',
          message: '已使用的激活码不可删除',
          type: 'warning'
        })
        return
      }
      
      // 构建确认消息，根据选中数量显示不同的提示
      let confirmMessage = ''
      if (idList.length === 1) {
        confirmMessage = '是否确认删除该激活码？'
      } else {
        confirmMessage = `是否确认删除选中的 ${idList.length} 个激活码？`
      }
      
      this.$confirm(confirmMessage, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delActivationCode(ids).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success'
            })
            this.getList()
          } else {
            this.$notify({
              title: '错误',
              message: response.msg || '删除失败',
              type: 'error'
            })
          }
        }).catch(error => {
          this.$notify({
            title: '错误',
            message: '网络请求失败，请稍后重试',
            type: 'error'
          })
          console.error('删除激活码失败:', error)
        })
      })
    },
    /** 取消按钮点击事件 */
    cancel() {
      // 确保表单验证不阻止弹窗关闭
      if (this.$refs.activationCodeRef && this.$refs.activationCodeRef.clearValidate) {
        this.$refs.activationCodeRef.clearValidate();
      }
      // 确保open值被正确设置为false
      this.open = false;
      this.reset();
    },
    
    /** 导出按钮点击事件 */
    handleExport() {
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['项目名称', '激活码', '状态', '激活码类型', '禁用状态', '积分', '有效类型', '有效值', '创建时间', '分配用户', '分配时间']
        const filterVal = ['proName', 'activeCode', 'status', 'activationType', 'disabled', 'mark', 'validityType', 'validityValue', 'createTime', 'allocateUserName', 'updateTime']
        const list = this.activationCodeList.map(item => {
          // 处理状态显示
          item.status = item.status === 0 ? '未使用' : (item.status === 1 ? '已使用' : '已过期')
          // 处理激活码类型显示
          item.activationType = item.activationType === 'MACHINE' ? '机器码限制' : '无限制'
          // 处理禁用状态显示
          item.disabled = item.disabled === 0 ? '启用' : '禁用'
          // 处理有效类型显示
          if (item.validityType) {
            const validityTypeMap = {
              'minute': '分钟',
              'hour': '小时',
              'day': '天',
              'month': '月',
              'year': '年',
              'permanent': '永久'
            }
            item.validityType = validityTypeMap[item.validityType] || item.validityType
          }
          // 格式化时间
          if (item.createTime) {
            item.createTime = this.parseTime(item.createTime, '{y}-{m}-{d} {h}:{i}:{s}')
          }
          if (item.updateTime) {
            item.updateTime = this.parseTime(item.updateTime, '{y}-{m}-{d} {h}:{i}:{s}')
          }
          return item
        })
        excel.export_json_to_excel({
          header: tHeader,
          data: this.formatJson(filterVal, list),
          filename: '激活码数据',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    
    /** 格式化JSON数据 */
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'proName') {
          // 如果没有proName字段，尝试从项目列表中获取
          return v.proName || this.getProjectName(v.proId) || ''
        }
        if (j === 'updateTime' && !v.updateTime) {
          return '-'
        }
        return v[j]
      }))
    },
    
    /** 重置表单数据 */
    resetForm(refName) {
      if (this.$refs[refName]) {
        this.$refs[refName].resetFields()
      }
    },
    
    /** 检查激活码是否可编辑 */
    checkEditable(row) {
      if (row.status === 1) {
        this.$notify({
          title: '提示',
          message: '已使用的激活码不可修改',
          type: 'warning'
        })
        return false
      }
      return true
    }
  }
}
</script>